package edu.purdue.cs.ds.vss;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

public class ShareStore {
 
	private ArrayList<Share> shares = new ArrayList<Share>();

	
	public ShareStore() {
		shares = null;
		shares = new ArrayList<Share>();
	}
	
	public ShareStore(ShareStore s){
		shares = new ArrayList<Share>();
		ArrayList<Share> sharesTmp = s.getShares();
		for(int i = 0; i < sharesTmp.size(); ++i){
			
			Share tmp = new Share(sharesTmp.get(i).getS(),
								sharesTmp.get(i).getIndex(),
								sharesTmp.get(i).getParentIndex());
			tmp.setR(sharesTmp.get(i).getR());
			tmp.setA(sharesTmp.get(i).getA());
			tmp.setLambda(sharesTmp.get(i).getLambda());
			
			update(tmp);
		}
	}
	
	public ShareStore(String fromDisk) {
		if(fromDisk.equals("")) {
			return;
		}
		
		StringTokenizer tok = new StringTokenizer(fromDisk, "\n");
		while(tok.hasMoreElements()) {
			String share = tok.nextToken();
			this.shares.add(new Share(share));
		}
		
	}
	
	public void update(Share share) {
		shares.add(share);
	}

	public ArrayList<Share> getShares() {
		return this.shares;
	}

	public void clear() {
		this.shares = new ArrayList<Share>();
	}

	@Override
	public String toString() {
		String ret = "Store : {\n";
		for (Iterator<Share> iterator = this.shares.iterator(); iterator.hasNext();) {
			Share share = iterator.next();
			ret += share.toString() + "\n";
		}
		ret += "\n}";
		
		return ret;
	}
	
	public String toDisk() {
		String ret = "";
		if(this.shares.size() == 0) return ret;
		
		for (Iterator<Share> iterator = this.shares.iterator(); iterator.hasNext();) {
			Share share = iterator.next();
			ret += share.toDisk() + "\n";
		}
		
		return ret.substring(0, ret.length()-1);
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof ShareStore) {
			ShareStore tmp = (ShareStore) obj;
			ArrayList<Share> tmpShares = tmp.getShares();
			if(tmpShares.size() != this.shares.size()) {
				return false;
			}
			
			for(int i = 0; i < tmpShares.size(); i++) {
				if(!tmpShares.get(i).equals(this.shares.get(i))) {
					return false;
				}
			}
			return true;
		} else {
			return false;
		}
	}
	
}
